<!--
 * @Author: your name
 * @Date: 2021-08-07 17:18:01
 * @LastEditTime: 2021-08-18 21:42:41
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \Self\hrsaas-86\src\views\employees\index.vue
-->
<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>共{{ total }}条记录</template>
        <template #right>
          <el-button
            size="small"
            type="danger"
            @click="$router.push('/import?type=user')"
          >
            excel导入
          </el-button>
          <el-button size="small" type="warning" @click="handleDownExcel">
            excel导出
          </el-button>
          <el-button size="small" type="primary" @click="showDialog = true">
            新增圆滚滚
          </el-button>
        </template>
      </page-tools>
      <!-- 员工表格 -->
      <el-card style="margin-top:20px">
        <el-table v-loading="loading" border :data="list">
          <el-table-column
            label="序号"
            sortable=""
            type="index"
            :index="indexMethod"
          />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img
                style="width:120px;height:120px;border-radius: 50%"
                v-imgerror="defaultImg"
                class="staff"
                :src="row.staffPhoto || defaultImg"
                alt=""
                @click="showCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <!-- 如果列添加了作用域插槽  el-table-column上的prop属性不再生效, 以作用域插槽为准 -->
          <!-- <el-table-column label="聘用形式" sortable="">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
            :formatter="formatter"
          />

          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">
                角色
              </el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top:20px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <!-- 添加员工的对话框 -->
      <add-employee :show-dialog.sync="showDialog" />
      <el-dialog
        :visible="showCodeVisible"
        title="头像预览"
        width="220px"
        @close="showCodeVisible = false"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色的对话框子组件 -->
      <assign-role
        :setRoleVisible.sync="setRoleVisible"
        :user-id="userId"
      ></assign-role>
    </div>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees.js'
import employeeMenu from '@/constant/employees'
import AddEmployee from './component/add-employee.vue'
import QrCode from 'qrcode'
import AssignRole from './component/assign-role.vue'

export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [], // 员工列表

      total: 0, //  员工总数
      page: 1,
      showCodeVisible: false, // 展示二维码对话框布尔值
      size: 5,
      loading: false,
      userId: '',
      setRoleVisible: false, // 角色对话框布尔值
      showDialog: false, // 控制新增员工的对话框的布尔值
      defaultImg:
        'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg'
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    // 获取圆滚滚列表
    async getEmployees() {
      this.loading = true
      const {
        data: { rows, total }
      } = await reqGetEmployeeList(this.page, this.size)
      this.list = rows
      this.total = total
      this.loading = false
    },
    // size发送变化触发的方法
    handleSizeChange(newval) {
      this.size = newval
      this.page = 1
      this.getEmployees()
    },
    // 页码发生变化触发的方法
    handleCurrentChange(newval) {
      this.page = newval
      this.getEmployees()
    },
    // 自定义索引列
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    // 聘用形式格式化列的方法
    formatter(row, column, cellValue, index) {
      // row 当前行的信息
      // column 是当前列的信息
      // cellValue 单元格的值
      // index 索引
      // console.log(row, column, cellValue, index)
      // return cellValue === 1 ? '正式员工' : '非正式员工'
      // console.log(employeeMenu.hireType)
      const obj = employeeMenu.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    delEmployee(id) {
      // 1.确认提示框
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          // 2.发送请求
          const { message } = await reqDelEmployee(id)
          // 3.提示信息
          this.$message.success(message)
          // bug page--
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          // 4.重新渲染数据
          this.getEmployees()
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    async handleDownExcel() {
      // 导入vendor文件夹下的某个模块
      // 性能问题 点击按钮后再去加载这个模块 提高性能

      const {
        data: { rows }
      } = await reqGetEmployeeList(1, this.total)

      console.log(rows) // 所有的员工列表数据
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 得到一个二维数组  this.get2Array最终的返回值是一个二维数组
      const arr2 = this.get2Array(rows, headersArr, headersRelations)
      console.log(arr2) // 二维数组
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          multiHeader,
          merges,
          header: headersArr,
          data: arr2,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },

    // 处理二维数组的方法 --未优化
    // 处理二维数组的方法 --未优化
    get2Array(rows, headersArr, headersRelations) {
      const res = rows.map(item => {
        // item是对象(每一个员工的详细信息)
        const arr = []
        headersArr.forEach(str => {
          // str是每一个headerArr的字符串
          const englishKey = headersRelations[str]
          //  将对应的每个人信息的对应的值追加到arr中
          // 聘用形式导出的数据是 正式/非正式  1 2
          if (englishKey === 'formOfEmployment') {
            const obj = employeeMenu.hireType.find(
              o => o.id === +item[englishKey]
            )
            const str = obj ? obj.value : '未知'
            arr.push(str)
          } else {
            arr.push(item[englishKey])
          }
        })
        return arr
      })
      // console.log(res)
      return res
    },
    // 点击图像展示二维码
    async showCode(info) {
      if (!info) return this.$message.info('默认头像无法展示')
      // console.log(11)
      this.showCodeVisible = true
      await await this.$nextTick()
      //  QrCode.toCanvas(dom元素,生成二维码的信息)
      QrCode.toCanvas(this.$refs.myCanvas, info)
    },
    // 分配角色
    editRole(id) {
      this.setRoleVisible = true
      this.userId = id
    }
  }
}
</script>

<style></style>
